package rocket;

import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendCallback;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;

/**
 * 异步生产者
 * @author wsz
 * @date 2022/2/22 18:29
 **/
public class AsyncProducer {

    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("producer_grp_wsz");
        producer.setNamesrvAddr("192.168.174.138:9876");
        producer.start();

        for (int i=0; i<100; i++) {
            Message message = new Message(
                    "tp_demo1",
                    ("hello lagou " + i).getBytes("utf-8")
            );

            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息发送成功:" +sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println("消息发送异常:" +throwable.getMessage());
                }
            });
        }

        // 异步发送，防止发送过程中断连接 由于是异步发送消息，上面循环结束之后，消息可能还没收到broker的响应
        Thread.sleep(10000);

        producer.shutdown();
    }
}
